package com.crm.system.service.impl.csd.customerManager;

import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.crm.common.model.DhPageInfo;
import com.crm.common.model.Enum.StatusCodeEnum;
import com.crm.common.model.Enum.csd.ContactExamineEnum;
import com.crm.common.model.Enum.csd.WorkLogEnum;
import com.crm.common.util.CommonUtils;
import com.crm.common.util.DateUtil;
import com.crm.common.util.ExcelUtil4;
import com.crm.model.entity.contactManager.Contact;
import com.crm.model.entity.contactManager.ContactExample;
import com.crm.model.entity.contactManager.ContactInformation;
import com.crm.model.entity.contactManager.ContactInformationExample;
import com.crm.model.entity.csd.customerManager.CustomerServiceWorkLog;
import com.crm.model.entity.customerManager.Customer;
import com.crm.model.entity.customerManager.CustomerContactPerson;
import com.crm.model.entity.customerManager.CustomerContactPersonExample;
import com.crm.model.entity.sys.UserAccount;
import com.crm.model.qo.csd.customerManager.ContactMaintainQO;
import com.crm.model.qo.csd.customerManager.ContactMaintainUpdateQO;
import com.crm.model.vo.csd.customerManager.ContactMaintainExportVO;
import com.crm.model.vo.csd.customerManager.ContactMaintainVO;
import com.crm.service.contactManager.ContactDbService;
import com.crm.service.contactManager.ContactInformationDbService;
import com.crm.service.csd.customerManager.ContactMaintainDbService;
import com.crm.service.csd.customerManager.CustomerServiceWorkLogDbService;
import com.crm.service.customerManager.CustomerContactPersonDbService;
import com.crm.service.customerManager.CustomerDbService;
import com.crm.system.service.csd.customerManager.ContactMaintainService;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import org.apache.commons.lang3.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.servlet.http.HttpServletResponse;
import java.net.URLEncoder;
import java.util.*;

/**
 * @author yincuimei
 * @Date 2021/10/25 15:37
 */
@Service
public class ContactMaintainServiceImpl implements ContactMaintainService {
    @Autowired
    private ContactMaintainDbService contactMaintainDbService;
    @Autowired
    private CustomerServiceWorkLogDbService workLogDbService;
    @Autowired
    private ContactDbService contactDbService;

    @Autowired
    private ContactInformationDbService contactInformationDbService;
    @Autowired
    private CustomerContactPersonDbService customerContactPersonDbService;
    @Autowired
    private CustomerDbService customerDbService;

    /**
     *(客服部)联系人管理》联系人维护列表
     * @param contactMaintainQO  --查询条件
     * @param pageIndex/pageSize --页码/分页大小
     * @param sortName/sortOrder --排序字段/排序规则(ASC/DESC)
     * @author yincuimei
     * @return
     */
    @Override
    public DhPageInfo<ContactMaintainVO> selectContactMaintainVOList(ContactMaintainQO contactMaintainQO, Integer pageIndex, Integer pageSize, String sortName, String sortOrder) {
        if (pageIndex != null && pageSize != null) {
            PageHelper.startPage(pageIndex, pageSize);
        }
        //排序
        StringBuilder order = new StringBuilder();
        if (!StringUtils.isBlank(sortName) && !StringUtils.isBlank(sortOrder)) {
            switch(sortName) {
                case "createTm": {
                    order.append("t.create_tm ").append(sortOrder);//创建时间
                }
                break;
                default:
                    break;
            }
        }
        List<ContactMaintainVO> contactMaintainVOList = contactMaintainDbService.selectContactMaintainVOList(contactMaintainQO,order.toString());
        PageInfo<ContactMaintainVO> pageInfo = new PageInfo(contactMaintainVOList);
        return new DhPageInfo<ContactMaintainVO>(pageInfo, contactMaintainVOList);
    }

    /**
     * 联系人维护--批量审核
     * @param contactIds  --联系人ID集合
     * @param examineInfo --审核信息(0-未审核 1-真实 2-错误)
     * @author yincuimei
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public JSONObject updateExamineByIdsBatch(List<String> contactIds, Integer examineInfo) {
        UserAccount userAccount = (UserAccount)SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String accountId = userAccount.getAccountId();//当前登录人账号
        String userName = userAccount.getUserName();//当前登录人姓名

        //返回结果
        JSONObject resultJson =  new JSONObject();
        if(contactIds != null && contactIds.size() > 0 && examineInfo != null){
            //1. 查询出所选中审核列数据库中联系人表信息
            List<Contact> dbContactList = contactMaintainDbService.selectContactListByIds(contactIds);

            //2. 修改联系人表(lxr_contact)
            Contact contact = new Contact();
            contact.setUpdatePeopleId(accountId);//更新人
            contact.setUpdateTm(new Date());//更新时间
            contact.setIsExamine(examineInfo);//审核信息
            Boolean result = contactMaintainDbService.updateExamineByIdsBatch(contactIds,contact);

            List<CustomerServiceWorkLog> workLogList =  new ArrayList<CustomerServiceWorkLog>();
            if(dbContactList != null && dbContactList.size() > 0){
                for(Contact dbContact : dbContactList){
                    CustomerServiceWorkLog workLog = new CustomerServiceWorkLog();
                    workLog.setWorkLogId(CommonUtils.getGUID());//主键
                    workLog.setLogType(WorkLogEnum.LOG_TYPE_CONTACT_MAINTAIN.getCode().shortValue());//日志类型
                    String dbExamine = dbContact.getIsExamine() != null ? ContactExamineEnum.getExamineMessage(dbContact.getIsExamine()):"";
                    String newExamine = examineInfo != null ? ContactExamineEnum.getExamineMessage(examineInfo) : "";
                    String contactName = dbContact.getContactName();//联系人名称
                    workLog.setLogContent("联系人维护: "+  userName + "将"+ contactName+ "的审核信息\""+ dbExamine + "\"改为" + newExamine);//日志内容
                    workLog.setCreateTm(new Date());//创建时间
                    workLog.setCreatePeopleId(accountId);//创建人
                    workLog.setUpdateTm(new Date());//更新时间
                    workLog.setUpdatePeopleId(accountId);//更新人
                    workLog.setCustomerId(dbContact.getCustomerId());//客户ID
                    workLog.setRelationId(dbContact.getContactId());//联系人ID
                    workLog.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));//删除状态
                    workLogList.add(workLog);
                }
            }

            //3. 批量添加工作日志，记录此次审核操作
            if(workLogList != null && workLogList.size() > 0){
                result = workLogDbService.insertWorkLogBatch(workLogList);
            }

            if(result){
                resultJson.put("code","000000");
                resultJson.put("message","审核成功");
                return resultJson;
            }
        }else{
            resultJson.put("code","000001");
            resultJson.put("message","请选中要审核的列");
            return resultJson;
        }
        return resultJson;
    }

    /**
     * 联系人维护-》修改
     * @param contactMaintainUpdateQO
     * @author yincuimei
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public JSONObject updateContactByContactId(ContactMaintainUpdateQO contactMaintainUpdateQO) {
        UserAccount userAccount = (UserAccount)SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String accountId = userAccount.getAccountId();//当前登录人账号
        String userName = userAccount.getUserName();//当前登录人姓名

        String contactId = contactMaintainUpdateQO.getContactId();//联系人ID
        String contactName = contactMaintainUpdateQO.getContactName();//联系人名称
        String contactInformation = contactMaintainUpdateQO.getContactInformation();//联系方式
        String customerId = contactMaintainUpdateQO.getCustomerId();//客户ID

        Date operateDate = new Date();

        //返回结果
        JSONObject resultJson = new JSONObject();
        if(!StringUtils.isBlank(contactId)){
            //1.根据联系方式查询联系人表(lxr_contact):查询数据库中是否有重复的联系方式
            ContactExample contactExample = new ContactExample();
            ContactExample.Criteria contactCriteria = contactExample.createCriteria();
            contactCriteria.andContactIdNotEqualTo(contactId);
            contactCriteria.andContactInformationEqualTo(contactInformation);
            Contact contactInformationIsRepeat = contactDbService.selectContactByExample(contactExample);
            if(contactInformationIsRepeat != null){
                resultJson.put("RP0000","联系方式已存在");
                return resultJson;
            }
            //2.根据联系人ID查询修改前数据库里的联系人信息
            Contact contact =  contactDbService.selectContactById(contactId);
            if(contact != null){
                Contact contactUpdate = new Contact();
                contactUpdate.setContactId(contact.getContactId());
                contactUpdate.setUpdatePeopleId(accountId);//更新人ID
                contactUpdate.setUpdateTm(operateDate);//更新时间
                contactUpdate.setContactName(contactName);//联系人名称
                contactUpdate.setContactInformation(contactInformation);//联系方式
                //3.修改联系人表(lxr_contact)
                contactDbService.updateContact(contactUpdate);
                //4.1 查询出要修改的联系方式数据(根据联系人ID、联系方式;备注：联系人表和联系方式表是一对多关系)
                ContactInformation information = contactInformationDbService.getContactIdAndContactInformation(contactId,contact.getContactInformation());
                //4.2 修改联系方式表(lxr_contact_information)
                if(information != null){
                    information.setUpdatePeopleId(accountId);
                    information.setUpdateTm(operateDate);
                    information.setContactInformation(contactInformation);
                    contactInformationDbService.updateContactInformation(information);
                }

                //5 企业联系人：修改客户联系人表数据(chs_customer_contact_person); 个人联系人：修改客户表联系人数据(chs_customer)
                Integer contactNature = contact.getContactNature();//联系人性质 0-企业联系人;1-个人联系人
                if(contactNature != null){
                    if(0 == contactNature){//企业联系人
                        //5.1 查询出需要修改的客户联系人(根据客户ID、联系人名称、联系方式、所属分公司、删除状态)
                        CustomerContactPerson customerContactPerson = customerContactPersonDbService.selectCustomerContactPerson
                                (contact.getCustomerId(),contact.getContactName(),contact.getContactInformation(),contact.getCompanyId());
                        //5.2 修改客户联系人
                        if(customerContactPerson != null){
                            customerContactPerson.setUpdatePeopleId(accountId);
                            customerContactPerson.setUpdateTm(operateDate);
                            customerContactPerson.setContactName(contactName);
                            customerContactPerson.setContactInformation(contactInformation);
                            customerContactPersonDbService.updateCustomerContactPerson(customerContactPerson);
                        }
                    }else if(1 == contactNature){//个人联系人
                        if(!StringUtils.isBlank(contact.getCustomerId())){
                            //6. 修改客户表联系人
                            Customer customer = new Customer();
                            customer.setCustomerId(contact.getCustomerId());
                            customer.setUpdatePeopleId(accountId);
                            customer.setUpdateTm(operateDate);
                            customer.setContactPerson(contactName);
                            customer.setContactPersonPhone(contactInformation);
                            customerDbService.updateCustomerById(customer);
                        }
                    }
                }

                //7. 添加工作日志(记录此次修改操作)
                String logContent = "";
                String oldContactName = contact.getContactName() != null ? contact.getContactName():"空";
                String newContactName = contactName != null?contactName:"空";
                String oldContactInformation = contact.getContactInformation() != null ? contact.getContactInformation() : "空";
                String newContactInformation = contactInformation != null ? contactInformation : "空";
                if(!oldContactName.equals(newContactName)){
                    logContent += "将联系人\""+ oldContactName + "\"改为\"" +newContactName+"\"";
                }
                if(!oldContactInformation.equals(newContactInformation)){
                    if(!StringUtils.isBlank(logContent)){
                        logContent += ";将联系方式\""+ oldContactInformation + "\"改为\"" +newContactInformation+"\"";
                    }else{
                        logContent += "将联系方式\""+ oldContactInformation + "\"改为\"" +newContactInformation+"\"";
                    }
                }
                if(!StringUtils.isBlank(logContent)){
                    CustomerServiceWorkLog workLog = new CustomerServiceWorkLog();
                    workLog.setWorkLogId(CommonUtils.getGUID());//主键
                    workLog.setLogType(WorkLogEnum.LOG_TYPE_CONTACT_MAINTAIN.getCode().shortValue());//日志类型
                    workLog.setLogContent(userName + logContent);//日志内容
                    workLog.setCreateTm(operateDate);//创建时间
                    workLog.setCreatePeopleId(accountId);//创建人
                    workLog.setUpdateTm(operateDate);//更新时间
                    workLog.setUpdatePeopleId(accountId);//更新人
                    workLog.setCustomerId(customerId);//客户ID
                    workLog.setRelationId(contactId);//联系人ID
                    workLog.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));//删除状态
                    workLogDbService.insertWorkLog(workLog);
                }
                resultJson.put("000000","联系人修改成功");
                return resultJson;
            }
        }
        resultJson.put("-1","服务器错误请稍后再试");
        return resultJson;
    }

    /**
     * 联系人维护-》删除(逻辑删除相关联的表)
     * @param contactId     --联系人ID
     * @param contactName   --联系人名称
     * @param customerId    --客户ID
     * @param contactNature --联系人性质(0:企业联系人;1:个人联系人)
     * @author yincuimei
     * @return
     */
    @Override
    @Transactional(rollbackFor = {RuntimeException.class, Error.class})
    public Boolean deleteContactByContactId(String contactId,String contactName,String customerId,Integer contactNature) {
        UserAccount userAccount = (UserAccount)SecurityUtils.getSubject().getPrincipal();//获取登录人信息
        String accountId = userAccount.getAccountId();//当前登录人账号
        String userName = userAccount.getUserName();//当前登录人用户名

        Short deleteStatus = Short.parseShort(String.valueOf(StatusCodeEnum.DELETE_CODE.getState()));
        Date date = new Date();
        Boolean result = false;


        if(!StringUtils.isBlank(contactId)){
            //根据联系人ID查询修改前数据库里的联系人信息
            Contact dbContact =  contactDbService.selectContactById(contactId);
            //1. 删除联系人表(lxr_contact)
            Contact contact = new Contact();
            contact.setContactId(contactId);
            contact.setUpdatePeopleId(accountId);
            contact.setUpdateTm(date);
            contact.setDeleteStatus(deleteStatus);
            contactMaintainDbService.deleteContactByContactId(contact);

            //2. 删除联系方式表(lxr_contact_information)
            ContactInformation contactInformation =  new ContactInformation();
            contactInformation.setUpdatePeopleId(accountId);
            contactInformation.setUpdateTm(date);
            contactInformation.setDeleteStatus(deleteStatus);
            ContactInformationExample example = new ContactInformationExample();
            ContactInformationExample.Criteria criteria = example.createCriteria();
            criteria.andContactIdEqualTo(contactId);
            contactMaintainDbService.deleteContactInformationByContactId(contactInformation,example);

            //3. 企业联系人删除(chs_customer_contact_person); 个人联系人删除(chs_customer)
            if(contactNature != null && !StringUtils.isBlank(customerId)){
                if(0 == contactNature){//企业联系人
                    CustomerContactPerson customerContactPerson = customerContactPersonDbService.selectCustomerContactPerson
                            (dbContact.getCustomerId(),dbContact.getContactName(),dbContact.getContactInformation(),dbContact.getCompanyId());
                    if(customerContactPerson != null){
                        customerContactPerson.setUpdatePeopleId(accountId);
                        customerContactPerson.setUpdateTm(date);
                        customerContactPerson.setDeleteStatus(deleteStatus);
                        CustomerContactPersonExample  contactPersonExample = new CustomerContactPersonExample();
                        CustomerContactPersonExample.Criteria contactPersonCriteria = contactPersonExample.createCriteria();
                        contactPersonCriteria.andCustomerIdEqualTo(customerId);
                        contactPersonCriteria.andCustomerContactPersonIdEqualTo(customerContactPerson.getCustomerContactPersonId());
                        customerContactPerson.setCustomerContactPersonId(null);//不修改主键
                        contactMaintainDbService.deleteCustomerContactPersonByCustomerId(customerContactPerson,contactPersonExample);
                    }
                }else if(1 == contactNature){//个人联系人
                    Customer customer = new Customer();
                    customer.setCustomerId(customerId);
                    customer.setUpdatePeopleId(accountId);
                    customer.setUpdateTm(date);
                    customer.setDeleteStatus(deleteStatus);
                    contactMaintainDbService.deleteCustomerByCustomerId(customer);
                }
            }

            //4. 添加工作日志(记录此次操作)
            CustomerServiceWorkLog workLog = new CustomerServiceWorkLog();
            workLog.setWorkLogId(CommonUtils.getGUID());//主键
            workLog.setLogType(WorkLogEnum.LOG_TYPE_CONTACT_MAINTAIN.getCode().shortValue());//日志类型
            workLog.setLogContent("联系人维护: "+  userName + "将联系人\""+ contactName + "\"删除");//日志内容
            workLog.setCreateTm(date);//创建时间
            workLog.setCreatePeopleId(accountId);//创建人
            workLog.setUpdateTm(date);//更新时间
            workLog.setUpdatePeopleId(accountId);//更新人
            workLog.setCustomerId(customerId);//客户ID
            workLog.setRelationId(contactId);//联系人ID
            workLog.setDeleteStatus(Short.parseShort(String.valueOf(StatusCodeEnum.NORMAL_CODE.getState())));//删除状态
            result = workLogDbService.insertWorkLog(workLog);
        }
        return result;
    }

    /**
     * 联系人维护-》导出
     * @param response
     * @param contactMaintainQO
     * @author yincuimei
     * @return
     */
    @Override
    public void exportContactMaintain(HttpServletResponse response, ContactMaintainQO contactMaintainQO) throws Exception{
        try{
            String fileName = URLEncoder.encode("联系人 "+ DateUtil.getDate("yyyy-MM-dd HH:mm:ss"), "UTF-8").replaceAll("\\+", "%20");
            response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
            HorizontalCellStyleStrategy horizontalCellStyleStrategy = ExcelUtil4.getHorizontalCellStyleStrategy();
            List<ContactMaintainVO> contactMaintainVOList = contactMaintainDbService.selectContactMaintainVOList(contactMaintainQO,"t.create_tm desc");
            List<ContactMaintainExportVO> contactMaintainExportVOList = new ArrayList<ContactMaintainExportVO>();
            if(contactMaintainVOList != null && contactMaintainVOList.size() > 0){
                for(ContactMaintainVO contactMaintainVO : contactMaintainVOList){
                    ContactMaintainExportVO contactMaintainExportVO = new ContactMaintainExportVO();
                    BeanUtils.copyProperties(contactMaintainVO,contactMaintainExportVO);
                    contactMaintainExportVOList.add(contactMaintainExportVO);
                }
            }
            //这里需要设置不关闭流
            EasyExcel.write(response.getOutputStream(), ContactMaintainExportVO.class)
                    .autoCloseStream(Boolean.FALSE)
                    .sheet("联系人")
                    .registerWriteHandler(horizontalCellStyleStrategy)
                    .doWrite(contactMaintainExportVOList);
        }catch(Exception e){
             //重置response
            response.reset();
            response.setContentType("application/json");
            response.setCharacterEncoding("utf-8");
            Map<String, String> map = new HashMap<String, String>();
            map.put("status", "failure");
            map.put("message", "下载文件失败" + e.getMessage());
            response.getWriter().println(JSON.toJSONString(map));
        }
    }
}
